package com.core136.service.news;

import com.core136.bean.account.Account;
import com.core136.bean.account.UserInfo;
import com.core136.bean.news.News;
import com.core136.bean.sys.MsgBody;
import com.core136.bean.sys.PageParam;
import com.core136.common.enums.GobalConstant;
import com.core136.common.utils.SysTools;
import com.core136.mapper.news.NewsMapper;
import com.core136.service.account.AccountService;
import com.core136.service.sys.MessageUnitService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
public class NewsService {
    private NewsMapper newsMapper;

    @Autowired
    public void setNewsMapper(NewsMapper newsMapper) {
        this.newsMapper = newsMapper;
    }

    private MessageUnitService messageUnitService;

    @Autowired
    public void setMessageUnitService(MessageUnitService messageUnitService) {
        this.messageUnitService = messageUnitService;
    }

    private AccountService accountService;

    @Autowired
    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    /**
     * @param news
     * @return int
     * @Title insertNews
     * @Description  发布
     */
    public int insertNews(News news) {
        return newsMapper.insert(news);
    }

    /**
     * @param news
     * @return int
     * @Title deleteNews
     * @Description  删除
     */
    public int deleteNews(News news) {
        return newsMapper.delete(news);
    }

    /**
     * @param news
     * @param example
     * @return int
     * @Title updateNews
     * @Description  更新
     */
    public int updateNews(News news, Example example) {
        return newsMapper.updateByExampleSelective(news, example);
    }

    /**
     * @param news
     * @return News
     * @Title selectOne
     * @Description  获取新闻详情
     */
    public News selectOneNews(News news) {
        return newsMapper.selectOne(news);
    }

    /**
     * @param @param  example
     * @param @return 设定文件
     * @return List<News> 返回类型
     * @Title: selectNewsList
     * @Description:  按条件获取新闻列表
     */
    public List<News> selectNewsList(Example example) {
        return newsMapper.selectByExample(example);
    }

    /**
     * @Title: sendNews
     * @Description:  发布新闻
     * @param: news
     * @param: @return
     * @return: int
     */
    public int sendNews(News news, UserInfo userInfo) {
        int flag = insertNews(news);
        if (flag > 0) {
            if (StringUtils.isNotBlank(news.getMsgType())) {
                List<MsgBody> msgBodyList = new ArrayList<MsgBody>();
                List<Account> accountList = accountService.getAccountInPriv(news.getOrgId(), news.getUserPriv(), news.getDeptPriv(), news.getLevelPriv());
                for (int i = 0; i < accountList.size(); i++) {
                    MsgBody msgBody = new MsgBody();
                    msgBody.setFromAccountId(news.getCreateUser());
                    msgBody.setFormUserName(userInfo.getUserName());
                    msgBody.setTitle(news.getNewsTitle());
                    msgBody.setContent(news.getSubheading());
                    msgBody.setSendTime(news.getSendTime());
                    msgBody.setAccount(accountList.get(i));
                    msgBody.setRedirectUrl("/mobile/news/details?newsId=" + news.getNewsId());
                    msgBody.setAttach(news.getAttach());
                    msgBody.setOrgId(news.getOrgId());
                    msgBodyList.add(msgBody);
                }
                messageUnitService.sendMessage(news.getMsgType(), GobalConstant.MSG_TYPE_NEWS, msgBodyList);
            }
        }
        return flag;
    }

    /**
     * 获取新闻维护列表
     */

    public List<Map<String, Object>> getNewsManageList(String orgId, String opFlag, String status, String accountId, String search) {
        return newsMapper.getNewsManageList(orgId, opFlag, status, accountId, "%" + search + "%");
    }


    public PageInfo<Map<String, Object>> getNewsManageList(PageParam pageParam, String status) throws Exception {
        PageHelper.startPage(pageParam.getPageNumber(), pageParam.getPageSize(), SysTools.escapeSqlStr(pageParam.getOrderBy()));
        List<Map<String, Object>> datalist = getNewsManageList(pageParam.getOrgId(), pageParam.getOpFlag(), status, pageParam.getAccountId(), pageParam.getSearch());
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(datalist);
        return pageInfo;
    }

    /**
     * @throws Exception
     * @Title: getMyNewsList
     * @Description:  获取个人权限内的新闻
     * @param: pageParam
     * @param: deptId
     * @param: levelId
     * @param: newsType
     * @param: status
     * @param: beginTime
     * @param: endTime
     * @param: @return
     * @return: PageInfo<Map < String, Object>>
     */
    public PageInfo<Map<String, Object>> getMyNewsList(PageParam pageParam, String deptId, String levelId, String newsType, String status, String beginTime, String endTime) throws Exception {
        PageHelper.startPage(pageParam.getPageNumber(), pageParam.getPageSize(), SysTools.escapeSqlStr(pageParam.getOrderBy()));
        List<Map<String, Object>> datalist = getMyNewsList(pageParam.getOrgId(), pageParam.getAccountId(), deptId, levelId, newsType, status, beginTime, endTime, pageParam.getSearch());
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(datalist);
        return pageInfo;
    }


    /**
     * 获取个人权限内的新闻
     */

    public List<Map<String, Object>> getMyNewsList(String orgId, String accountId, String deptId, String levelId, String newsType, String status, String beginTime, String endTime, String search) {
        return newsMapper.getMyNewsList(orgId, accountId, deptId, levelId, newsType, status, beginTime, endTime, "%" + search + "%");
    }

    /**
     * @param @param  orgId
     * @param @param  accountId
     * @param @param  deptId
     * @param @param  levelId
     * @param @param  newsId
     * @param @return 设定文件
     * @return News 返回类型
     * @Title: getReadNews
     * @Description:  阅读
     */
    public Map<String, Object> getReadNews(String orgId, String accountId, String deptId, String levelId, String newsId) {
        News news = new News();
        news.setOrgId(orgId);
        news.setNewsId(newsId);
        news = selectOneNews(news);
        List<String> list = new ArrayList<String>();
        String readuser = news.getReader();
        if (StringUtils.isNotBlank(readuser)) {
            String[] userArr;
            if (readuser.indexOf(",") > 0) {
                userArr = readuser.split(",");
            } else {
                userArr = new String[]{readuser};
            }
            for (int i = 0; i < userArr.length; i++) {
                if (StringUtils.isNotBlank(userArr[i])) {
                    list.add(userArr[i]);
                }
            }
        }
        list.add(accountId);
        HashSet<String> h = new HashSet<String>(list);
        list.clear();
        list.addAll(h);
        this.updateReadStatus(orgId, accountId, deptId, levelId, newsId, StringUtils.join(list, ","));
        return newsMapper.getReadNewsById(orgId, newsId);
    }

    /**
     * 更新新闻点点击次数
     */

    public int updateReadStatus(String orgId, String accountId, String deptId, String levelId, String newsId, String reader) {
        //  Auto-generated method stub
        return newsMapper.updateReadStatus(orgId, accountId, deptId, levelId, newsId, reader);
    }

    /**
     * 获取阅读新闻详情
     */

    public Map<String, Object> getReadNewsById(String orgId, String newsId) {
        //  Auto-generated method stub
        return newsMapper.getReadNewsById(orgId, newsId);
    }

    /**
     * @Title: getMyNewsListForDesk
     * @Description:  我的桌面上的新闻
     * @param: orgId
     * @param: accountId
     * @param: deptId
     * @param: levelId
     * @param: @return
     * @return: List<Map < String, String>>
     */
    public List<Map<String, String>> getMyNewsListForDesk(String orgId, String endTime, String accountId, String deptId, String levelId) {
        return newsMapper.getMyNewsListForDesk(orgId, endTime, accountId, deptId, levelId);
    }

    public List<Map<String, String>> getMyPicNewsListForDesk(String orgId, String endTime, String accountId, String deptId, String levelId) {
        List<Map<String, String>> retMapList = new ArrayList<Map<String, String>>();
        List<Map<String, String>> resMapList = newsMapper.getMyPicNewsListForDesk(orgId, endTime, accountId, deptId, levelId);
        for (int i = 0; i < resMapList.size(); i++) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("newsId", resMapList.get(i).get("newsId"));
            map.put("newsTitle", resMapList.get(i).get("newsTitle"));
            Document htmlDoc = Jsoup.parse(resMapList.get(i).get("content"));
            Elements els = htmlDoc.getElementsByTag("img");
            for (int k = 0; k < els.size(); k++) {
                Element el = els.get(k);
                String imgUrl = el.attr("src");
                if (StringUtils.isNotBlank(imgUrl)) {
                    map.put("imgUrl", imgUrl);
                    break;
                }
            }
            retMapList.add(map);
        }
        return retMapList;
    }

    /**
     * @Title: getMobileMyNewsList
     * @Description:  获取移动端企业新闻列表
     * @param: orgId
     * @param: accountId
     * @param: deptId
     * @param: levelId
     * @param: page
     * @param: @return
     * @return: List<Map < String, String>>
     */
    public List<Map<String, String>> getMobileMyNewsList(String orgId, String accountId, String deptId, String levelId, Integer page) {
        return newsMapper.getMobileMyNewsList(orgId, accountId, deptId, levelId, page);
    }

    /**
     * 获取新闻人员查看状态
     *
     * @param orgId
     * @param newsId
     * @param list
     * @return
     */
    public List<Map<String, String>> getNewsReadStatus(String orgId, String newsId, List<String> list) {
        return newsMapper.getNewsReadStatus(orgId, newsId, list);
    }

}
